package com.newear.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import com.newear.bean.VersionUpgrade;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;



/**
 * SharedPreference工具类
 * Created by josan_tang on 2016/07/19.
 */
public class MySharedPreferences {

    private static final String SHAREDPREFERENCES_NAME = "thats";
    private static volatile MySharedPreferences instance;

    private MySharedPreferences() {
    }

    /**
     * 得到实例
     *
     * @return
     */
    public static MySharedPreferences getInstance() {
        if (instance == null) {
            synchronized (MyConstant.class) {
                if (instance == null) {
                    instance = new MySharedPreferences();
                }
            }
        }
        return instance;
    }

    /**
     * @return 得到顾客总量
     */
    public int getCustomerNumber(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getInt("customerNum", 0);
    }

    /**
     * 设置顾客总量
     */
    public void setCustomerNum(Context context, int customerNum) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("customerNum", customerNum);
        editor.apply();
    }


    /**
     * 设置用户id
     *
     * @param context
     */
    public void setUserId(Context context, String userId) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("urid", userId);
        editor.apply();
    }

    /**
     * 得到用户名id,如果没有用户名，返回""
     *
     * @param context
     * @return
     */
    public String getUserId(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        String urid = preferences.getString("urid", "");
        return urid;
    }

    /**
     * 设置用户name
     *
     * @param context
     */
    public void setUsername(Context context, String username) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("username", username);
        editor.apply();
    }

    /**
     * 得到用户名
     *
     * @param context
     * @return
     */
    public String getUsername(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getString("username", "");
    }

    /**
     * 设置用户密码
     *
     * @param context
     */
    public void setPassword(Context context, String password) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("password", password);
        editor.apply();
    }

    /**
     * 得到用户密码
     *
     * @param context
     * @return
     */
    public String getPassword(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getString("password", "");
    }

    /**
     * 是否记住登录密码
     *
     * @param context
     */
    public void setKeepSign(Context context, boolean isKeepSign) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("iskeepsign", isKeepSign);
        editor.apply();
    }

    /**
     * 得到用户是否保持登录
     *
     * @param context
     * @return
     */
    public boolean getKeepSign(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getBoolean("iskeepsign", false);
    }

    /**
     * 设置Direcotry页面Neayby选中的tag
     *
     * @param context
     */
    public void setDirectoryNearbyTag(Context context, String tag) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("directory_neayby", tag);
        editor.apply();
    }

    /**
     * 得到Direcotry页面Neayby选中的tag
     *
     * @param context
     * @return
     */
    public String getDirectoryNearbyTag(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getString("directory_neayby", "");
    }

    /**
     * 设置Direcotry页面Category选中的tag
     *
     * @param context
     */
    public void setDirectoryCategoryTag(Context context, String tag) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("directory_category", tag);
        editor.apply();
    }

    /**
     * 得到Direcotry页面Category选中的tag
     *
     * @param context
     * @return
     */
    public String getDirectoryCategoryTag(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getString("directory_category", "");
    }

    /**
     * 设置Direcotry页面Region选中的tag
     *
     * @param context
     */
    public void setDirectoryRegionTag(Context context, String tag) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("directory_region", tag);
        editor.apply();
    }

    /**
     * 得到Direcotry页面Region选中的tag
     *
     * @param context
     * @return
     */
    public String getDirectoryRegionTag(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getString("directory_region", "");
    }


    /**
     * 设置是否已经引导过了，如果是，下次不再引导
     */
    public void setGuided(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        editor.putBoolean("isFirstIn", false);
        //提交数据
        editor.apply();
    }


    /**
     * 得到是否已经引导过了
     *
     * @param context
     */
    public boolean getGuided(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getBoolean("isFirstIn", true);
    }

    /**
     * 设置不再提示更新
     */
    public void setNeverUpdate(Context context, boolean neverUpdate) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        editor.putBoolean("neverUpdate", neverUpdate);
        //提交数据
        editor.apply();
    }

    /**
     * 得到是否设置过不再更新
     *
     * @param context
     */
    public boolean getNeverUpdate(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getBoolean("neverUpdate", false);
    }



    /**
     * 得到发布失败信息
     *
     * @param context
     */
    public String getPublishDiscussFail(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        String publishDiscuss = preferences.getString("publishdiscuss", "");
        return publishDiscuss;
    }

    /**
     * 设置发布失败信息
     *
     * @param context
     */
    public void setPublishDiscussFail(Context context, String publishDiscuss) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        editor.putString("publishdiscuss", publishDiscuss);
        editor.apply();
    }

    /**
     * 得到当天是否需要检查
     *
     * @param context
     */
    public boolean getCurDayDontUpdate(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        String lastDontUpdateTime = preferences.getString("setupdate", "");
        if (Validator.isEffective(lastDontUpdateTime)) {
            if (lastDontUpdateTime.equals(DataConverter.getCurDayTime("yyyy-MM-dd"))) {
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    /**
     * 设置当天不需要更新
     *
     * @param context
     */
    public void setCurDayDontUpdate(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        String curDayTime = DataConverter.getCurDayTime("yyyy-MM-dd");
        //存入数据
        editor.putString("setupdate", curDayTime);
        editor.apply();
    }

    /**
     * 得到是否更新软件
     *
     * @param context
     */
    public boolean getUpdateApk(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        boolean updateapk = preferences.getBoolean("updateapk", false);
        return updateapk;
    }

    /**
     * 是否更新软件
     *
     * @param context
     */
    public void setUpdateApk(Context context, boolean updateApk) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        editor.putBoolean("updateapk", updateApk);
        editor.apply();
    }

    /**
     * 根据key和预期的value类型获取value的值
     *
     * @param key
     * @param clazz
     * @return
     */
    public <T> T getValue(Context context, String key, Class<T> clazz) {
        if (context == null) {
            throw new RuntimeException("请先调用带有context，name参数的构造！");
        }
        SharedPreferences sp = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return getValue(key, clazz, sp);
    }

    /**
     * 针对复杂类型存储<对象>
     *
     * @param key
     * @param object
     */
    public void setObject(Context context, String key, Object object) {
        SharedPreferences sp = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        try {

            out = new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, objectVal);
            editor.apply();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T getObject(Context context, String key, Class<T> clazz) {
        SharedPreferences sp = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        if (sp.contains(key)) {
            String objectVal = sp.getString(key, null);
            byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
                T t = (T) ois.readObject();
                return t;
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bais != null) {
                        bais.close();
                    }
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 对于外部不可见的过渡方法
     *
     * @param key
     * @param clazz
     * @param sp
     * @return
     */
    @SuppressWarnings("unchecked")
    private <T> T getValue(String key, Class<T> clazz, SharedPreferences sp) {
        T t;
        try {
            t = clazz.newInstance();
            if (t instanceof Integer) {
                return (T) Integer.valueOf(sp.getInt(key, 0));
            } else if (t instanceof String) {
                return (T) sp.getString(key, "");
            } else if (t instanceof Boolean) {
                return (T) Boolean.valueOf(sp.getBoolean(key, false));
            } else if (t instanceof Long) {
                return (T) Long.valueOf(sp.getLong(key, 0L));
            } else if (t instanceof Float) {
                return (T) Float.valueOf(sp.getFloat(key, 0L));
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
            MyLogger.e("system", "类型输入错误或者复杂类型无法解析[" + e.getMessage() + "]");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            MyLogger.e("system", "类型输入错误或者复杂类型无法解析[" + e.getMessage() + "]");
        }
        MyLogger.e("system", "无法找到" + key + "对应的值");
        return null;
    }

    /**
     * 设置版本信息
     *
     * @param context
     */
    public void setVersion(Context context, VersionUpgrade info) {
        try {
            SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            String serializeStr = serialize(info);
            editor.putString("versionupgrade", serializeStr);
            editor.apply();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到版本信息
     *
     * @param context
     */
    public VersionUpgrade getVersion(Context context) {
        try {
            SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
            String serializeStr = preferences.getString("versionupgrade", "");
            if (Validator.isEffective(serializeStr)) {
                return (VersionUpgrade) deSerialization(serializeStr);
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 设置Token
     *
     * @param context
     */
    public void setToken(Context context, String token) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("token", token);
        editor.apply();
    }

    /**
     * 得到Token
     *
     * @param context
     * @return
     */
    public String getToken(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getString("token", "");
    }

    /**
     * 序列化对象
     *
     * @return
     * @throws IOException
     */
    private String serialize(Object object) throws IOException {
        long startTime = System.currentTimeMillis();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        String serStr = byteArrayOutputStream.toString("ISO-8859-1");
        serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
        objectOutputStream.close();
        byteArrayOutputStream.close();
        MyLogger.d("serial", "serialize str =" + serStr);
        long endTime = System.currentTimeMillis();
        MyLogger.d("serial", "序列化耗时为:" + (endTime - startTime));
        return serStr;
    }

    /**
     * 反序列化对象
     *
     * @param str
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private Object deSerialization(String str) throws IOException,
            ClassNotFoundException {
        long startTime = System.currentTimeMillis();
        String redStr = java.net.URLDecoder.decode(str, "UTF-8");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                redStr.getBytes("ISO-8859-1"));
        ObjectInputStream objectInputStream = new ObjectInputStream(
                byteArrayInputStream);
        Object object = objectInputStream.readObject();
        objectInputStream.close();
        byteArrayInputStream.close();
        long endTime = System.currentTimeMillis();
        MyLogger.d("serial", "反序列化耗时为:" + (endTime - startTime));
        return object;
    }


}
